#include <vector>
#include <string>
#include <sstream>
#include <iostream>
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Codec {
public:
    std::stringstream ss;
    int index=0;
    // Encodes a tree to a single string.
    std::string serialize(TreeNode* root) {
        ser(root);
        return ss.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(std::string data) {
        std::vector<std::string> nodes;
        // 手动分割字符串，比使用istringstream更高效
        size_t pos = 0;
        while (pos < data.size()) {
            size_t nextPos = data.find(',', pos);
            if (nextPos == std::string::npos) nextPos = data.size();
            
            nodes.push_back(data.substr(pos, nextPos - pos));
            pos = nextPos + 1;
        }
        
        return  deset(nodes);
    }

    void ser(TreeNode *root)
    {
        if (!root) {
            ss << "#,";
            return;
        }
        
        ss << root->val << ",";
        ser(root->left);
        ser(root->right);
    }
TreeNode* deset(const std::vector<std::string>& nodes)
    {
     if (nodes[index]=="#")
     {
         index++;
         return nullptr;
     }
       TreeNode* now = new TreeNode(std::stoi(nodes[index++]));
        now->left = deset(nodes);
        now->right = deset(nodes);
        return now;
    }
    
    
};

